package com.songcha.library_common.ui.dialog

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.TextView
import androidx.compose.ui.text.style.TextAlign
import androidx.constraintlayout.widget.ConstraintLayout
import com.songcha.library_common.R
import com.songcha.library_common.helper.ViewHelper
import com.songcha.library_common.ui.view.CustomButton
import com.songcha.library_common.ui.view.CustomContainerLayout
import com.songcha.library_common.util.dp2px



open class CustomDialog
@JvmOverloads
constructor(context:Context,theme:Int=0) : Dialog(context,theme){

    private var mWidth:Int? = null
    private var mHeight:Int? = null
    private var mGravity:Int = Gravity.CENTER
    private var mTitle:String = "提示"
    private var mMsg:String = "msg"
    private var mConfirmListener:(()->Boolean)? = null
    private var mCancelListener:(()->Boolean)? = null
    private var mAnim:Int = R.style.dialogScaleWindowAnim
    private var mView: View? = null
    private var mIsViewMatchParent = false
    private var mCancelOnTouchOutside = true
    private var mCancelable = true
    private var mShowBtn = true
    private var mCancelText = "取消"
    private var mConfirmText = ""
    private var mRadius = floatArrayOf()
    private var mIsShowShadow = false
    private var mShadowWidth = 0f
    private var mTitleColor = Color.BLACK
    private var mTitleTextSize = 18f
    private var mTitleMarginTop = 10f.dp2px()
    private var mIsImmerse = false
    private var mBackgroundColor:Int? = Color.WHITE
    private var mDimAmount = 0.5f
    private var mMsgTextAlign = View.TEXT_ALIGNMENT_CENTER

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.common_dialog_custom)
        initDialog()
    }

    fun setDialogTitle(title:String){
        mTitle=title
    }

    fun getDialogTitle():String{
        return mTitle
    }

    fun setDialogMsg(msg:String){
        mMsg = msg
    }

    fun setSize(width:Int,height:Int){
        setWidth(width)
        setHeight(height)
    }

    fun setWidth(width:Int){
        mWidth=width
    }

    fun setHeight(height:Int){
        mHeight=height
    }

    fun setGravity(gravity: Int){
        mGravity=gravity
    }

    fun setAnim(anim:Int){
        mAnim=anim
    }

    fun setTitleTextSize(textSize:Float){
        mTitleTextSize=textSize
    }

    fun setOnConfirmListener(block:()->Boolean) {
        mConfirmListener=block
    }

    fun setOnCancelListener(block:()->Boolean) {
        mCancelListener=block
    }

    fun setShowBtn(showBtn:Boolean){
        mShowBtn=showBtn
    }

    fun setCancelText(cancelText:String){
        mCancelText=cancelText
    }

    fun setConfirmText(confirmText:String){
        mConfirmText=confirmText
    }

    protected open fun getView(root: ViewGroup):View?{
        return null
    }

    fun setRadius(radius: Float){
        val radiusArr = FloatArray(4)
        for(i in 0 until 4){
            radiusArr[i] = radius
        }
        mRadius=radiusArr
    }

    fun setRadius(radius: FloatArray){
        mRadius=radius
    }

    fun custom(radius:Float = 0f){
        setDialogTitle("")
        setDialogMsg("")
        setShowBtn(false)
        setRadius(floatArrayOf(radius))
        setBackgroundColor(Color.TRANSPARENT)
    }

    protected open fun setTitleColor(color:Int){
        mTitleColor=color
    }

    protected open fun setTitleMarginTop(top: Float){
        mTitleMarginTop=top
    }

    protected open fun setCancelOnTouchOutside(can: Boolean){
        mCancelOnTouchOutside=can
    }

    protected open fun setCanCancelable(can: Boolean){
        mCancelable=can
    }

    protected open fun setShowShadow(show: Boolean){
        mIsShowShadow=show
    }

    protected open fun setShadowWidth(width: Float){
        mShadowWidth=width
    }

    fun setBackgroundColor(color: Int){
        mBackgroundColor=color
    }

    fun setIsImmerse(isImmerse:Boolean){
        mIsImmerse=isImmerse
    }

    fun setDimAmount(amount:Float){
        if(amount<0f || amount>1f) return
        mDimAmount=amount
    }

    fun setMsgTextAlign(align:Int){
        mMsgTextAlign = align
    }

    override fun onStart() {
        super.onStart()
        // window?.setWindowAnimations(R.style.dialogWindowAnim)
    }

    /*protected fun getTitleHeight():Int{
        return 38.dp2px()
    }*/
    /**
     * custom view must return true
     */
    protected open fun hasView():Boolean{
        return false
    }


    private fun initDialog(){

        window?.attributes?.apply {
            width = if(mWidth!=null){
                mWidth!!
            }else{
                300f.dp2px().toInt()
            }

            if(mHeight!=null)
                height=mHeight!!

            alpha=1f

        }

        //set background translate,otherwise some attributes such round and width not effective
        window?.apply {
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            setGravity(mGravity)
            setWindowAnimations(mAnim)
            setDimAmount(mDimAmount)
        }

        if(mIsImmerse){
            window?.decorView?.systemUiVisibility = (
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    )
            window?.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window?.statusBarColor = Color.TRANSPARENT
        }

        setCanceledOnTouchOutside(mCancelOnTouchOutside)
        setCancelable(mCancelable)

        val cclParent=findViewById<CustomContainerLayout>(R.id.common_dialog_ccl)
        if(mIsShowShadow && mShadowWidth>0f){
            //TODO set shadow
            //cclParent.setShowShadow(true)
            //cclParent.setShadowBlur(mShadowWidth)
        }

        if(mBackgroundColor!=null){
            cclParent.setContainerBackgroundColor(mBackgroundColor!!)
        }


        val tvTitle=findViewById<TextView>(R.id.tv_title).apply{text=mTitle}
        val tvMsg=findViewById<TextView>(R.id.tv_msg).apply{text=mMsg}
        tvMsg.textAlignment = mMsgTextAlign

        val clBtn=findViewById<ConstraintLayout>(R.id.cl_btn)

        val showTitle=mTitle.isNotBlank()
        val showMsg=mMsg.isNotBlank()

        if(showTitle){
            tvTitle.setTextColor(mTitleColor)
            tvTitle.textSize=mTitleTextSize
            (tvTitle.layoutParams as ConstraintLayout.LayoutParams).topMargin = mTitleMarginTop.toInt()
        }else{
            (tvMsg.layoutParams as ConstraintLayout.LayoutParams).topMargin = 0
        }


        if(mRadius.isNotEmpty())
            cclParent.setRadius(mRadius)

        val clDialog=findViewById<ConstraintLayout>(R.id.cl_dialog)
        val line1=findViewById<View>(R.id.line1)

        ViewHelper.setVisibility(showTitle,tvTitle)

        ViewHelper.setVisibility(showMsg,tvMsg)

        ViewHelper.setVisibility(mShowBtn,clBtn,line1)


        if(mHeight!=null){
            clDialog.layoutParams.height=mHeight!!
            if(mShowBtn){
                clBtn.layoutParams=clBtn.layoutParams.apply {
                    this as ConstraintLayout.LayoutParams
                    topToBottom=-1
                    bottomToBottom=ConstraintLayout.LayoutParams.PARENT_ID
                }
                line1.layoutParams=line1.layoutParams.apply {
                    this as ConstraintLayout.LayoutParams
                    topToBottom=-1
                    bottomToTop=clBtn.id
                }
            }
        }

        if(!showTitle && showMsg && !mShowBtn){
            val tvMsgLp = ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT,ConstraintLayout.LayoutParams.WRAP_CONTENT)
            tvMsgLp.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID
            tvMsgLp.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID
            tvMsgLp.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
            tvMsgLp.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID
            tvMsg.layoutParams = tvMsgLp
        }


        if(hasView()){
            val viewContainer=FrameLayout(context)
            viewContainer.id=View.generateViewId()
            val viewContainerLp:ConstraintLayout.LayoutParams
            if(mHeight!=null){
                viewContainerLp=ConstraintLayout.LayoutParams(0,0)
            }else{
                viewContainerLp=ConstraintLayout.LayoutParams(0,ConstraintLayout.LayoutParams.WRAP_CONTENT)
            }

            viewContainerLp.leftToLeft=ConstraintLayout.LayoutParams.PARENT_ID
            viewContainerLp.rightToRight=ConstraintLayout.LayoutParams.PARENT_ID

            if(showMsg){
                viewContainerLp.topToBottom=tvMsg.id
                viewContainerLp.topMargin=10.dp2px()
            }else if(showTitle){
                viewContainerLp.topToBottom=tvTitle.id
                viewContainerLp.topMargin=10.dp2px()
            }else{
                viewContainerLp.topToTop=ConstraintLayout.LayoutParams.PARENT_ID
            }

            if(mShowBtn){
                line1.layoutParams.apply {
                    this as ConstraintLayout.LayoutParams
                    if(mHeight!=null){
                        viewContainerLp.bottomMargin=10.dp2px()
                    }else{
                        topToBottom=viewContainer!!.id
                    }
                }
                viewContainerLp.bottomToTop=line1.id

            }else{
                viewContainerLp.bottomToBottom=ConstraintLayout.LayoutParams.PARENT_ID
            }
            viewContainer.layoutParams=viewContainerLp
            //viewContainer.setBackgroundColor(Color.RED)

            mView=getView(viewContainer)
            if(mView==null){
                throw Exception("exception by has view and get view return null")
            }

            viewContainer.addView(mView)
            clDialog.addView(viewContainer)
        }

        /*if(mView==null)
            mView=getView(clDialog)
        if(mView!=null){
            if(mTitle.isEmpty())
                tvTitle.visibility=View.GONE


            if(mHeight!=null)
                clDialog.layoutParams.height=mHeight!!

            lateinit var lp:ConstraintLayout.LayoutParams
            if(mView!!.layoutParams==null){
                if(mIsViewMatchParent){
                    lp=ConstraintLayout.LayoutParams(0, 0)
                    lp.bottomToBottom=ConstraintLayout.LayoutParams.PARENT_ID
                }else{
                    lp=ConstraintLayout.LayoutParams(0,ConstraintLayout.LayoutParams.WRAP_CONTENT)
                }
            }else{
                lp=mView!!.layoutParams as ConstraintLayout.LayoutParams
            }
            lp.leftToLeft=ConstraintLayout.LayoutParams.PARENT_ID
            lp.rightToRight=ConstraintLayout.LayoutParams.PARENT_ID

            if(mMsg.isEmpty()){
                tvMsg.visibility=View.GONE
                lp.topToBottom=R.id.tv_title
            }else{
                lp.topToBottom=R.id.tv_msg
            }


            if(mView!!.id==-1){
                mView!!.id=ConstraintLayout.generateViewId()
            }
            mView!!.layoutParams=lp

            clDialog.addView(mView)

            val line1=findViewById<View>(R.id.line1)
            if(mShowBtn){
                line1.layoutParams.apply {
                    this as ConstraintLayout.LayoutParams
                    topToBottom=mView!!.id
                }
            }else{
                line1.visibility=View.GONE
                clBtn.visibility=View.GONE
            }

        }*/


        val btnConfirm=findViewById<CustomButton>(R.id.btn_confirm)
        btnConfirm.setOnClickListener{
            if(mConfirmListener!=null){
                if(mConfirmListener!!()) dismiss()
            } else{
                dismiss()
            }

        }

        val line2=findViewById<View>(R.id.line2)
        val btnCancel=findViewById<CustomButton>(R.id.btn_cancel)
        if(mCancelText.isBlank()){
            btnCancel.visibility=View.GONE
            line2.visibility=View.GONE
        }else{
            btnCancel.text=(mCancelText)

            btnCancel.setOnClickListener{
                if(mCancelListener!=null){
                    if(mCancelListener!!()) dismiss()
                }else{
                    dismiss()
                }

            }
        }

        if(mConfirmText.isNotBlank())
            btnConfirm.text=(mConfirmText)
    }


    //builder mode
    companion object{
        class Builder{
            private var mContext:Context?=null
            private var mTitle:String="提示"
            private var mMsg:String=""
            private var mWidth:Int?=null
            private var mHeight:Int?=null
            private var mGravity:Int=Gravity.CENTER
            private var mConfirmListener:(()->Boolean)?=null
            private var mCancelListener:(()->Boolean)?=null
            private var mAnim:Int=R.style.dialogScaleWindowAnim
            private var mTheme:Int=0
            //private var mView:View?=null
            //private var mIsViewMatchParent=false
            private var mCancelOnTouchOutside=true
            private var mCancelable=true
            private var mShowBtn=true
            private var mCancelText="取消"
            private var mConfirmText=""
            private var mRadius=floatArrayOf()
            private var mIsShowShadow=false
            private var mShadowWidth=0f
            private var mTitleColor=Color.BLACK
            private var mTitleTextSize=18f
            private var mTitleMarginTop=10f.dp2px()
            private var mIsImmerse=false
            private var mBackgroundColor:Int?=Color.WHITE
            private var mDimAmount=0.5f
            private var mMsgTextAlign = View.TEXT_ALIGNMENT_CENTER

            constructor(context: Context){
                this.mContext=context
            }

            fun setDialogTitle(title:String): Builder {
                mTitle=title
                return this
            }

            fun setDialogMsg(msg:String): Builder {
                mMsg=msg
                return this
            }

            fun setWidth(width:Int): Builder {
                mWidth=width
                return this
            }


            fun setHeight(height:Int): Builder {
                mHeight=height
                return this
            }

            fun setGravity(gravity:Int): Builder {
                mGravity=gravity
                return this
            }

            fun setAnim(anim:Int): Builder {
                mAnim=anim
                return this
            }

            /*fun setView(view:View,isMatchParent:Boolean=false): Builder {
                mView=view
                mIsViewMatchParent=isMatchParent
                return this
            }*/

            fun setTheme(theme:Int): Builder {
                mTheme=theme
                return this
            }

            fun setCancelOnTouchOutside(cancelOnTouchOutside:Boolean): Builder {
                mCancelOnTouchOutside=cancelOnTouchOutside
                return this
            }

            fun setCanCancelable(cancelable:Boolean): Builder {
                mCancelable=cancelable
                return this
            }

            fun setOnConfirmListener(block:()->Boolean): Builder {
                mConfirmListener=block
                return this
            }

            fun setOnCancelListener(block:()->Boolean): Builder {
                mCancelListener=block
                return this
            }

            fun setShowBtn(showBtn:Boolean):Builder{
                mShowBtn=showBtn
                return this
            }

            fun setCancelText(cancelText:String):Builder{
                mCancelText=cancelText
                return this
            }

            fun setConfirmText(confirmText:String):Builder{
                mConfirmText=confirmText
                return this
            }

            fun setRadius(radius:FloatArray):Builder{
                mRadius=radius
                return this
            }

            fun setRadius(radius: Float):Builder{
                val radiusArr = FloatArray(4)
                for(i in 0 until 4){
                    radiusArr[i] = radius
                }
                mRadius=radiusArr
                return this
            }

            fun setShowShadow(showShadow:Boolean):Builder{
                mIsShowShadow=showShadow
                return this
            }

            fun setShadowWidth(shadowWidth:Float):Builder{
                mShadowWidth=shadowWidth
                return this
            }

            fun setTitleColor(color:Int):Builder{
                mTitleColor=color
                return this
            }

            fun setTitleTextSize(textSize:Float):Builder{
                mTitleTextSize=textSize
                return this
            }

            fun setTitleMarginTop(marginTop:Float):Builder{
                mTitleMarginTop=marginTop
                return this
            }

            fun setIsImmerse(isImmerse: Boolean):Builder{
                mIsImmerse=isImmerse
                return this
            }

            fun setBackgroundColor(color:Int):Builder{
                mBackgroundColor=color
                return this
            }

            fun setDimAmount(amount:Float):Builder{
                if(amount<0f || amount>1f) return this
                mDimAmount=amount
                return this
            }

            fun setMsgTextAlign(align:Int):Builder{
                mMsgTextAlign = align
                return this
            }


            fun create(): CustomDialog {
                val dialog= CustomDialog(mContext!!,mTheme)
                dialog.mTitle=mTitle
                dialog.mMsg=mMsg
                dialog.mConfirmListener=mConfirmListener
                dialog.mCancelListener=mCancelListener
                dialog.mAnim=mAnim
                if(mWidth!=null){
                    dialog.mWidth=mWidth
                }
                if(mHeight!=null){
                    dialog.mHeight=mHeight
                }
                dialog.mGravity=mGravity
                dialog.mCancelOnTouchOutside=mCancelOnTouchOutside
                dialog.mCancelable=mCancelable
                dialog.mShowBtn=mShowBtn
                dialog.mCancelText=mCancelText
                dialog.mConfirmText=mConfirmText
                dialog.mRadius=mRadius
                dialog.mTitleColor=mTitleColor
                dialog.mTitleTextSize=mTitleTextSize
                dialog.mTitleMarginTop=mTitleMarginTop
                dialog.mIsImmerse=mIsImmerse
                dialog.mBackgroundColor=mBackgroundColor
                dialog.mDimAmount=mDimAmount
                dialog.mMsgTextAlign = mMsgTextAlign
                return dialog
            }

        }
    }

}